package com.zpf.web.filter;

import com.zpf.pojo.User;
import com.zpf.service.UserService;
import com.zpf.service.impl.UserServiceImpl;
import com.zpf.utils.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class AutoLoginFilter implements Filter {
    @Override//创建过滤器
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    //实现自动登录
    /*
    * 0.验证是否登录，登录成功则放行，没有登录则自动登录
    * 1.从cookie获取用户信息
    * 2.验证码账户，密码是否正确
    * 3.如果正确，登录成功
    *
    * */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //从session中获取用户信息
        Object user = request.getSession().getAttribute("user");
        //如果登录了则放行
        if (user != null) {
            filterChain.doFilter(request,response);
            return;
        }

        //自动登录
        //获取cookie
        Cookie[] cookie = request.getCookies();
        if (cookie == null || cookie.length == 0) {
            response.sendRedirect("/login.jsp");
        }
        //循环cookie
        for (Cookie cookie1 : cookie) {
            String name = cookie1.getName();
            //查找需要的用户信息
            if("userinfo-2202".equals(name)){
                String value = cookie1.getValue();
                //解密:admin 123456
                String userInfo = Base64Utils.decode(value);
                String[] arr = userInfo.split("#");
                if(arr != null && arr.length == 2){
                    UserService userService = new UserServiceImpl();
                    User login = userService.login(arr[0],arr[1]);
                    if (login != null) {
                        request.getSession().setAttribute("user",login);
                        response.sendRedirect("/index.jsp");
                       break;
                    }
                }

            }
        }
        //最后泛型
            filterChain.doFilter(request,response);
    }

    @Override//销毁过滤器
    public void destroy() {

    }
}
